import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // 获取存储在本地的token
    let token=''
    const userinfo = localStorage.getItem('userinfo');
    if(userinfo){
      const parsedUserinfo = JSON.parse(userinfo);
      token = parsedUserinfo.token;
    }
    if(token){
      const cloned = req.clone({
        headers: req.headers.set('Authorization', `Bearer ${token}`)
      });
      return next.handle(cloned);
    }else {
        return next.handle(req);
      }
  }
}
